// SPDX-License-Identifier: GPL-2.0

#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>

#include "dim_core_status.h"
#include "dim_core_init.h"

MODULE_LICENSE("GPL");

#define DIM_SWITCH_ON "on"

static int interval;
module_param(interval, int, 0);

static int __init dim_setup(char *str)
{
	if (strncmp(str, DIM_SWITCH_ON, strlen(DIM_SWITCH_ON)) == 0)
		dim_set_running_status(DIM_NO_BASELINE);
	else
		dim_set_running_status(DIM_OFF);
	return 0;
}
__setup("dim=", dim_setup);

static int __init dim_interval_setup(char *str)
{
	unsigned long val;

	if (kstrtoul(str, 0, &val))
		val = 0;
	interval = val;
	return 0;
}
__setup("dim_interval=", dim_interval_setup);

static int __init dim_core_init(void)
{
	int ret;
#if IS_MODULE(CONFIG_EULEROS_DIM_CORE)
	dim_setup(DIM_SWITCH_ON);
#endif
	if (dim_get_running_status() == DIM_OFF) {
		pr_info("dim core off\n");
		return 0;
	}
	dim_init_running_status();

	ret = dim_init_env();
	if (ret != 0)
		return ret;

	ret = dim_init_baseline();
	if (ret != 0)
		goto err;

	ret = dim_init_timer(interval);
	if (ret != 0)
		goto err;

	pr_info("dim core on\n");
	return 0;

err:
	dim_uninit_timer();
	dim_uninit_baseline();
	dim_uninit_env();
	return ret;
}

static void __exit dim_core_exit(void)
{
	dim_lock_running_status_waiting();
	dim_uninit_timer();
	dim_uninit_baseline();
	dim_uninit_env();
}

#if IS_BUILTIN(CONFIG_EULEROS_DIM_CORE)
late_initcall(dim_core_init);
#elif IS_MODULE(CONFIG_EULEROS_DIM_CORE)
module_init(dim_core_init);
#endif
module_exit(dim_core_exit);
